package com.lz.demo2;

import java.util.concurrent.TimeUnit;

/**
 * @Description: Positive 通过使用关键字volatile修饰共享变量stopThread
 * 根据volatile的可见性原则可以保证主线程main函数修改了共享变量stopThread状态后对线程th来说是立即可见的
 * 所以在两秒内线程th将停止循环。
 * @Date: 2020/5/5 11:40
 * @Author: LiZhen
 * @Version: 1.0
 */
public class Positive {
    private static volatile boolean stopThread;
    public static void main(String[] args) throws InterruptedException {
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (!stopThread) {
                    i++;
                }
            }
        });
        th.start();
        TimeUnit.SECONDS.sleep(2);
        stopThread = true;
    }
}
